//
// Created by ct on 2021/9/16.
//
#include "lib/common.h"

int main(int argc, char *argv[]) {
    int listenfd, connfd;
    socklen_t clilen;
    struct sockaddr_un cliaddr, servaddr;

    listenfd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (listenfd < 0) { error(1, errno, "socket create failed"); }

    char *local_path = "/home/ct/unixstream.sock";
    // 我们这里还做了一个 unlink 操作，以便把存在的文件删除掉，这样可以保持幂等性。
    unlink(local_path);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sun_family = AF_LOCAL;
    strcpy(servaddr.sun_path, local_path);

    if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { error(1, errno, "bind failed"); }

    if (listen(listenfd, LISTENQ) < 0) { error(1, errno, "listen failed"); }

    clilen = sizeof(cliaddr);

    if ((connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen)) < 0) {
        error(1, errno, "accept failed");
    }

    char buf[BUFFER_SIZE];

    while (1) {
        bzero(buf, sizeof(buf));
        if (read(connfd, buf, BUFFER_SIZE) == 0) {
            printf("client quit");
            break;
        }
        printf("Receive: %s", buf);
        char send_line[MAXLINE];
        sprintf(send_line, "Hi, %s", buf);
        int nbytes = sizeof(send_line);
        if (write(connfd, send_line, nbytes) != nbytes) error(1, errno, "write error");
    }
    close(listenfd);
    close(connfd);

    exit(0);

    //return 0;
}